//
//  PartyDownoadRefreshController.m
//  UESTCPioneer
//
//  Created by Apple on 14-9-28.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PartyDownoadRefreshController.h"
#import "PioneerNewsEntity.h"
#import "UPTitleCell.h"
#import "UPMainInfoCell.h"
#import "UPFooterCell.h"
#import "PartyFullContentController.h"
#import "PartyDataLearnEntity.h"
#import "PartyDownloadDetailController.h"

static NSString *customTitleCellIndentifier = @"CustomTitleCellIndentifier";
static NSString *customMainCellIndentifier = @"CustomMainCellIndentifier";
static NSString *customFooterCellIndentifier = @"CustomFooterCellIndentifier";
@interface PartyDownoadRefreshController ()<UPMainInfoCellDelegate,UPTitleCellDelegate,UPFooterCellDelegate,downLoadFinishDelegate>
{
    NSMutableDictionary *_cellHeightDictionary;
}

@end

@implementation PartyDownoadRefreshController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.tableView registerClass:[UPTitleCell class] forCellReuseIdentifier:customTitleCellIndentifier];
    [self.tableView registerClass:[UPMainInfoCell class] forCellReuseIdentifier:customMainCellIndentifier];
    [self.tableView registerClass:[UPFooterCell class] forCellReuseIdentifier:customFooterCellIndentifier];
    _cellHeightDictionary=[[NSMutableDictionary alloc]init];
    //@AGPhotoBrowser
    AGPhotoBrowserView *photoBrowser = [[AGPhotoBrowserView alloc]init];
}

#pragma mark - refresh request
-(void)pullDownRefresh:(MJRefreshBaseView *)refreshView{
    [PublicMethod ClearEntity:entityName];
    [NetworkCenter RKRequestWithData:requestData EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
        NSMutableArray *dic = [[NSMutableArray alloc]init];
        [dic addObjectsFromArray:resultArray];
        tableViewEntitiesArray=[[NSArray alloc]initWithArray:dic];
        
        [self.tableView reloadData];
        PullUpRefreshTimes=0;
        [refreshView endRefreshing];
    } failure:^(NSError *error) {
        [refreshView endRefreshing];
        [Alert showAlert:@"刷新失败!"];
    }];
}
-(void)pullUpRefresh:(MJRefreshBaseView *)refreshView{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:requestData];
    [dic setObject:[NSString stringWithFormat:@"%d",PullUpRefreshTimes+2] forKey:@"page"];
    
    [NetworkCenter RKRequestWithData:dic EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
        
        if ([resultArray count]==0){
            [refreshView endRefreshing];
            return ;
        }
        
        NSMutableArray *newArray = [[NSMutableArray alloc]init];
        [newArray addObjectsFromArray:tableViewEntitiesArray];
        [newArray addObjectsFromArray:resultArray];
        NSArray *result = [[NSArray alloc]initWithArray:newArray];
        
        tableViewEntitiesArray=result;
        [self.tableView reloadData];
        
        //清除core data 因为现在还没有适合下拉刷新和适合本地缓存的api
        
        [refreshView endRefreshing];
        PullUpRefreshTimes++;
        
    } failure:^(NSError *error) {
        [Alert showAlert:@"刷新失败！"];
        [refreshView endRefreshing];
    }];
}

#pragma mark - 全文按钮事件
-(BOOL)ScreenTouch{
    return NO;
}

-(void)WholeNewsButtonClick:(NSInteger)theId{
    
    // 因为暂时无法实现在线阅读功能，所以暂时禁掉该方法
    return;
    
    BOOL result = [self ScreenTouch];
    if (result) {
        return;
    }
    
    PartyDataLearnEntity *entity = [PublicMethod entity:@"PartyDataLearnEntity" WithId:theId];
    NSString * filePath = [NSString stringWithFormat:@"%@%@",baseUrl,entity.filePath];
    NSURL * fileUrl = [NSURL URLWithString:filePath];
    NSURLRequest *request = [NSURLRequest requestWithURL:fileUrl];
    UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [webView loadRequest:request];
    [webView setScalesPageToFit:YES];
    webView.scrollView.bounces = NO;
    UIViewController * controller = [[UIViewController alloc] init];
    [controller.view addSubview:webView];
    [self.leveyTabBarController.navigationController pushViewController:controller animated:YES];
}

#pragma mark - tableView Cell dequeue
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PartyDataLearnEntity *entity= tableViewEntitiesArray[indexPath.section];
    if (indexPath.row == 0) {
        //6.0后用这种方式更直接，可以省掉if（cell2＝＝nil）的判断   @黄卓越 2014-3-28
        UPTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:customTitleCellIndentifier forIndexPath:indexPath];
        cell.theId=[entity.theId integerValue];
        
        [cell setTitle:entity.fileName];
        [cell setTime:entity.time];
        
        /*修改*/
        cell.indexPath = indexPath;
        /**/
        return cell;
    }
    else if (indexPath.row == 1) {
        //6.0后用这种方式更直接，可以省掉if（cell2＝＝nil）的判断   @黄卓越 2014-3-28
        UPMainInfoCell *cell2 = [tableView dequeueReusableCellWithIdentifier:customMainCellIndentifier forIndexPath:indexPath];
        _cellHeightDictionary[@(indexPath.section)]=@(110);
        [cell2 setNewsBody:entity.fileContent];
        cell2.theId=[entity.theId integerValue];
        cell2.delegate=self;
        cell2.btnLabel.hidden = YES;
        cell2.wordsLabel.frame = CGRectMake(5, 3, 290, 110);
        return cell2;
    }
    else {
        UPFooterCell * cell3;
        cell3 = [tableView dequeueReusableCellWithIdentifier:customFooterCellIndentifier forIndexPath:indexPath];
        
        for (UIView * view in  cell3.contentView.subviews) {
            if (view.tag == 100) {
                [view removeFromSuperview];
            }
        }
        
        cell3.theId=[entity.theId integerValue];
        cell3.delegate=self;
        
        [cell3 setCommentVisiable:NO];
        [cell3 setDownloadVisiable:YES];
        
        [cell3 setDownloadEntity:entity];
        [cell3 addDownloadButtonTarget:self Action:@selector(downloadButtonClick:)];
        return cell3;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height;
    if (indexPath.row == 0) {
        height = 55;
    } else if (indexPath.row == 1){
        height = 110;
    } else {
        height = 40;
    }
    return height;
}

-(void)downloadButtonClick:(commentButton *)btn{
    
    PartyDataLearnEntity * entity = (PartyDataLearnEntity *)btn.entity;
    
    NSLog(@"entity.fileName = %@,entity.theId = %@,entity.filePath = %@",entity.fileName,entity.theId,entity.filePath);
    NSString * urlStr;
    urlStr = [baseUrl stringByAppendingString:entity.filePath];
    PartyDownloadDetailController * viewController = [[PartyDownloadDetailController alloc ] initWithFileName:entity.fileName URLString:urlStr fileSize:entity.size theId:entity.theId];
    viewController.downLoadFinishDelegate = self;
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark downLoadFinishDelegate代理方法
-(void)downLoadFinishWithIndexPath:(NSNumber *)status  fileTheId:(NSNumber *)fileTheId{
    PartyDataLearnEntity * entity;
    for (int i = 0; i <tableViewEntitiesArray.count; i ++) {
        entity = tableViewEntitiesArray[i];
        NSLog(@"entity = %@",entity);
        NSLog(@"entity.theId = %@,fileTheId =%@",entity.theId,fileTheId);
        if([entity.theId isEqualToNumber:fileTheId]) {
            NSLog(@"status = %@,entity.isDownload = %@",status,entity.isDownload);
            entity.isDownload = status;
            break;
        }
    }
    [self.tableView reloadData];
}
@end

